// src/utils/sockjs-service.ts
import SockJS from 'sockjs-client'


// // 将 SockJS 实例挂载到 window 以便调试（仅开发环境）
// if (import.meta.env.DEV) {
//   window.SockJS = SockJS
// }



export class SockJSService {
  private sock: SockJS | null = null
  private url: string
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectInterval = 3000

  // 回调函数
  private messageCallbacks: ((data: any) => void)[] = []
  private openCallbacks: (() => void)[] = []
  private closeCallbacks: (() => void)[] = []
  private errorCallbacks: ((err: any) => void)[] = []

  constructor(url: string) {
    this.url = url
    this.connect()
  }

  public connect() {
    this.sock = new SockJS(this.url)

    this.sock.onopen = () => {
      this.reconnectAttempts = 0
      this.openCallbacks.forEach(cb => cb())
    }

    this.sock.onmessage = (e) => {
      try {
        const data = JSON.parse(e.data)
        this.messageCallbacks.forEach(cb => cb(data))
      } catch (err) {
        console.error('消息解析错误:', err)
      }
    }

    this.sock.onclose = () => {
      this.closeCallbacks.forEach(cb => cb())
      this.reconnect()
    }

    this.sock.onerror = (err) => {
      console.error('SockJS 错误:', err)
      this.errorCallbacks.forEach(cb => cb(err))
    }
  }

  private reconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      setTimeout(() => this.connect(), this.reconnectInterval)
    }
  }

  public send(data: any) {
    if (this.sock && this.sock.readyState === SockJS.OPEN) {
      this.sock.send(JSON.stringify(data))
    }
  }

  public close() {
    this.sock?.close()
  }

  // 注册回调
  public onMessage(callback: (data: any) => void) {
    this.messageCallbacks.push(callback)
  }

  public onOpen(callback: () => void) {
    this.openCallbacks.push(callback)
  }

  public onClose(callback: () => void) {
    this.closeCallbacks.push(callback)
  }

  public onError(callback: (err: any) => void) {
    this.errorCallbacks.push(callback)
  }
}